package zlog

import (
	"context"
	"fmt"
	"io"
	"os"
	"time"
)

func newLocalLogger(ctx context.Context) *LocalLogger {
	return &LocalLogger{
		Logger: Logger{
			ctx:    ctx,
			name:   "",
			sn:     "",
			prefix: "",
			suffix: "",
		},
	}
}

// SetSn 设置sn
func (l *LocalLogger) SetSn() Factory {
	l.sn = sn()
	return l
}

// SetFix 设置fix
func (l *LocalLogger) SetFix() Factory {
	return l
}

// SetFile 设置file
func (l *LocalLogger) SetFile(name string) Factory {
	l.writer = fileHandle(name)
	return l
}

func (l *LocalLogger) Info(msg string, fields ...Field) {
	if l.writer == nil {
		return
	}
	_, _ = l.writer.Write([]byte(l.format("Info", msg, fields...)))
}
func (l *LocalLogger) Debug(msg string, fields ...Field) {
	if l.writer == nil {
		return
	}
	_, _ = l.writer.Write([]byte(l.format("Debug", msg, fields...)))
}
func (l *LocalLogger) Error(msg string, fields ...Field) {
	if l.writer == nil {
		return
	}
	_, _ = l.writer.Write([]byte(l.format("Error", msg, fields...)))
}
func (l *LocalLogger) Sql(msg string, fields ...Field) {
	if l.writer == nil {
		return
	}
	_, _ = l.writer.Write([]byte(l.format("Sql", msg, fields...)))
}

// writers 获取句柄
func fileHandle(name string) io.Writer {
	if writer, has := writers.Load(name); has {
		return writer.(io.Writer)
	}

	logLock.Lock()
	defer logLock.Unlock()

	path := fmt.Sprintf("%s/%s.log", DefConfig.Dir, name)
	file, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
	if err == nil {
		writers.Store(name, file)
		_, _ = file.Write([]byte(time.Now().Format("2006-01-02 15:04:05.000000") + " 初始化日志句柄 " + name + "\n"))

		return file
	}

	panic(any(fmt.Sprintf("日志:%s句柄获取失败[%s]", name, err.Error())))
}
